
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html

from zfapple.base_admin import BaseAdmin
from blog.models import (
        Category, Tag, Article
    )


@admin.register(Category)
class CategoryAdmin(BaseAdmin):
    list_display = ('name', 'status', 'is_nav', 'create_time', 'article_count')
    fields = ('name', 'status', 'is_nav')

    def article_count(self, obj):
        return obj.article_set.count()

    article_count.short_description = '文章数量'


@admin.register(Tag)
class TagAdmin(BaseAdmin):
    list_display = ('name', 'status', 'create_time')
    fields = ('name', 'status')


@admin.register(Article)
class ArticleAdmin(BaseAdmin):
    list_display = [
        'title', 'category', 'status', 'create_time', 'operator'
    ]
    list_display_links = []
    list_filter = ['category', ]
    search_fields = ['title', 'category__name']
    actions_no_top = True
    fieldsets = (
        ('基础配置', {
            'description': '基础配置描述',
            'fields': (
                ('title', 'category'),
                'status'
            ),
        }),
        ('内容', {
            'fields': (
                'content',
                'desc',
            ),
        }),
        ('额外信息', {
            'classes': ('collapse',),
            'fields': ('tag',),
        }),
    )

    filter_vertical = ('tag', )

    def operator(self, obj):
        return format_html(
            '<a href="{}">编辑</a>',
            reverse('admin:blog_article_change', args=(obj.id,))
        )

    operator.short_description = '操作'
